package cn.b.sky.mes.em.controller;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.b.sky.mes.em.enums.MaintainTaskStatus;
import cn.b.sky.mes.em.model.MaintainTaskCause;
import cn.b.sky.mes.em.model.condition.MaintainTaskCondition;
import cn.b.sky.mes.em.service.MaintainConfigService;
import cn.b.sky.mes.em.service.MaintainTaskService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.mes.em.model.MaintainTask;
import cn.b.sky.mes.em.model.MaintainTaskPart;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import org.apache.commons.lang3.StringUtils;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.mes.cm.enums.ECodeEnums;
import cn.b.sky.user.service.ECodeService;
import cn.b.sky.user.service.model.ECode;

import com.alibaba.fastjson.JSON;

@Controller
@RequestMapping(value = "/maintainTask/*")
public class MaintainTaskController extends SecurityController {
  @Resource
  MaintainTaskService maintainTaskService;

  @Resource
  private ECodeService eCodeService;

  @Resource
  MaintainConfigService maintainConfigService;

  @RequestMapping("maintainTaskList")
  public String maintainTaskList(Model model, @ModelAttribute("condition") MaintainTaskCondition task, String navTabId) {
    task.setSiteCode(SecurityContextUtil.getSiteCode());
    if (StringUtils.isEmpty(task.getOrderField())) {
      task.setOrderField("plannedMaintainDate");
    }
    task.setLanguageCode(SecurityContextUtil.getLanguageCode());
    task.setStatusECodeType(ECodeEnums.MAINTAINTASKSTATUS.getCode());
    List<MaintainTask> taskList = maintainTaskService.selectMaintainTaskByCondition(task);
    int count = maintainTaskService.selectMaintainTaskCount(task);
    task.setData(taskList);
    task.setTotalCount(count);
    List<ECode> status = eCodeService.selectECodeList(ECodeEnums.MAINTAINTASKSTATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute("status", status);
    model.addAttribute("page", task);
    model.addAttribute(NAVTABID, navTabId);
    return "em/maintainTask/maintainTask_list";
  }

  @RequestMapping("addMaintainTask")
  public String addMaintainTask(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    return "em/maintainTask/maintainTask_add";
  }

  @RequestMapping("modifyMaintainTask")
  public String modifyMaintainTask(Model model, String navTabId, String id) {
    MaintainTask task = maintainTaskService.selectMaintainTaskByCode(getSiteCode(), id);
    task.setMaintainUser(SecurityContextUtil.getCurrentUserName());
    task.setMaintainEndDateTime(new Date());
    List<ECode> status = eCodeService.selectECodeList(ECodeEnums.MAINTAINTASKSTATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    List<MaintainTaskCause> causes = maintainTaskService.selectMaintainTaskCauseList(getSiteCode(), id);
    List<MaintainTaskPart> parts = maintainTaskService.selectMaintainTaskPartList(getSiteCode(), id);
    model.addAttribute("causes", causes);
    model.addAttribute("parts", parts);
    model.addAttribute("status", status);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("task", task);
    return "em/maintainTask/maintainTask_edit";
  }

  @RequestMapping("viewMaintainTask")
  public String viewMaintainTask(Model model, String navTabId, String id) {
    MaintainTask task = maintainTaskService.selectMaintainTaskByCode(getSiteCode(), id);
    task.setMaintainUser(SecurityContextUtil.getCurrentUserName());
    List<ECode> status = eCodeService.selectECodeList(ECodeEnums.MAINTAINTASKSTATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    List<MaintainTaskCause> causes = maintainTaskService.selectMaintainTaskCauseList(getSiteCode(), id);
    List<MaintainTaskPart> parts = maintainTaskService.selectMaintainTaskPartList(getSiteCode(), id);
    model.addAttribute("status", status);
    model.addAttribute("causes", causes);
    model.addAttribute("parts", parts);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("task", task);
    return "em/maintainTask/maintainTask_view";
  }

  @RequestMapping("saveMaintainTask")
  @ResponseBody
  public DWZResult saveMaintainTask(Model model, String navTabId, MaintainTask maintainTask, String isSave, String id,
      String failureCause, String part) {
    if (maintainTask == null) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }
    maintainTask.setSiteCode(getSiteCode());
    setCreateInfo(maintainTask);
    if (StringUtils.isEmpty(id)) {
      maintainTask.setUnPlannedFlag(1);
      maintainTask.setStatusECode(MaintainTaskStatus.PLAN.getValue());
      maintainTaskService.insertMaintainTask(maintainTask);
      return dialogAjaxDone(
          getImeViewMessageI18n(null, "successfulOperation.M"),
          null, null, null, null);
    } else {
      List<MaintainTaskCause> causes = null;
      if (!StringUtils.isEmpty(failureCause)) {
        causes = new ArrayList<MaintainTaskCause>();
        String[] failureCauses = failureCause.split(",");
        for (String s : failureCauses) {
          MaintainTaskCause cause = new MaintainTaskCause();
          cause.setSiteCode(getSiteCode());
          cause.setTaskCode(maintainTask.getTaskCode());
          cause.setFailureCauseCode(s);
          setCreateInfo(cause);
          causes.add(cause);
        }
      }
      List<MaintainTaskPart> parts = null;
      if (!StringUtils.isEmpty(part)) {
        parts = new ArrayList<MaintainTaskPart>();
        String[] ps = part.split(",");
        for (String s : ps) {
          String[] pa = s.split("&");
          MaintainTaskPart p = new MaintainTaskPart();
          p.setSiteCode(getSiteCode());
          p.setTaskCode(maintainTask.getTaskCode());
          p.setPartCode(pa[0]);
          p.setQuantity(Long.parseLong(pa[1]));
          setCreateInfo(p);
          parts.add(p);
        }
      }
      if ("1".equals(isSave)) {
        maintainTaskService.updateMaintainTask(maintainTask, causes, parts);
      } else {
        maintainTaskService.doSubmitMaintainTask(maintainTask, causes, parts);
      }
      return dialogAjaxDone(
          getImeViewMessageI18n(null, "successfulOperation.M"),
          null, null, null, null);

    }
  }

  @RequestMapping("executeMaintainTask")
  @ResponseBody
  public DWZResult executeMaintainTask(Model model, String navTabId, String id, HttpServletRequest request) {
    if (StringUtils.isEmpty(id)) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }
    String ids = request.getParameter("ids");
    String[] ress = ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(ress.length);
    boolean hasFail = false;
    for (String res : ress) {
      BatchJobReport report = maintainTaskService.doExecuteMaintainTask(getSiteCode(), res);
      reports.add(report);
      if (!report.isSuccess()) {
        hasFail = true;
      }
    }
    if (!hasFail) {
      // 直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null,
          getImeViewMessageI18n(null, "successfulOperation.M"),
          null);
    } else {
      return batchjobAjaxDone(request, reports);
    }

  }

  @RequestMapping("checkedButtonEnable")
  @ResponseBody
  public DWZResult checkedButtonEnable(String taskCode, String type) {
    MaintainTask task = maintainTaskService.selectMaintainTaskByCode(getSiteCode(), taskCode);
    String statusCode = task.getStatusECode();
    if (null != task && !MaintainTaskStatus.EXECUTE.getValue().equals(statusCode)) {
      return ajaxError(this.getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "maintainTaskCanNotEdit.M"));
    }

    return ajaxDone(null);
  }

  @RequestMapping("addPart")
  public String addPart(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    return "em/maintainTask/maintainTaskPart_add";
  }

  @RequestMapping("savePart")
  @ResponseBody
  public DWZResult saveProcessComponent(MaintainTaskPart part, Integer popId, Model model) {

    return ajaxDone(part);
  }

  @RequestMapping("cancelMaintainTask")
  @ResponseBody
  public DWZResult cancelMaintainTask(Model model, String navTabId, String id, HttpServletRequest request) {
    if (StringUtils.isEmpty(id)) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }
    String ids = request.getParameter("ids");
    String[] ress = ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(ress.length);
    boolean hasFail = false;
    for (String res : ress) {
      BatchJobReport report = maintainTaskService.doCancelMaintainTask(getSiteCode(), res);
      reports.add(report);
      if (!report.isSuccess()) {
        hasFail = true;
      }
    }
    if (!hasFail) {
      // 直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null,
          getImeViewMessageI18n(null, "successfulOperation.M"),
          null);
    } else {
      return batchjobAjaxDone(request, reports);
    }

  }

  @RequestMapping("maintainTaskCalendar")
  public String maintainTaskCalendar(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("lan", SecurityContextUtil.getLanguageCode());
    return "em/maintainTask/maintainTaskCalendar";
  }

  @RequestMapping("getEvents")
  @ResponseBody
  public List<Map<String, String>> getEvents(Model model, String start, String end) {
    List<Map<String, String>> result = new ArrayList<Map<String, String>>();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Date startDay = df.parse(start, new ParsePosition(0));
    Date endDay = df.parse(end, new ParsePosition(0));
    List<MaintainTask> tasks = maintainTaskService.selectMaintainTaskCountForCal(getSiteCode(), startDay, endDay);
    for (MaintainTask task : tasks) {
      Map<String, String> map = new HashMap<String, String>();
      map.put("title", Integer.toString(task.getCount()));
      map.put("start", df.format(task.getPlannedMaintainDate()));
      result.add(map);
    }
    return result;
  }

  @RequestMapping(value = "viewTaskDetail")
  @ResponseBody
  public DWZResult viewTaskDetail(String type, String date) {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Date day = df.parse(date, new ParsePosition(0));
    MaintainTask task = new MaintainTask();
    task.setSiteCode(SecurityContextUtil.getSiteCode());
    task.setLanguageCode(SecurityContextUtil.getLanguageCode());
    if ("plan".equals(type)) {
      task.setStatusECode(MaintainTaskStatus.PLAN.getValue());
    } else if ("execute".equals(type)) {
      task.setStatusECode(MaintainTaskStatus.EXECUTE.getValue());
    } else if ("cancel".equals(type)) {
      task.setStatusECode(MaintainTaskStatus.CANCEL.getValue());
    } else if ("done".equals(type)) {
      task.setStatusECode(MaintainTaskStatus.DONE.getValue());
    }
    task.setStatusECodeType(ECodeEnums.MAINTAINTASKSTATUS.getCode());
    task.setPlannedMaintainDate(day);
    List<MaintainTask> details = maintainTaskService.selectMaintainTaskByDate(task, day, day);
    String orderDetailsJSON = JSON.toJSONString(details);
    return ajaxDone(orderDetailsJSON);
  }

  @RequestMapping(value = "selectDay")
  @ResponseBody
  public DWZResult selectDay(String date) {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Date day = df.parse(date, new ParsePosition(0));
    MaintainTask task = maintainTaskService.selectMaintainTaskCountDeatilForCal(getSiteCode(), day);
    String taskJSON = JSON.toJSONString(task);
    return ajaxDone(taskJSON);
  }

  @RequestMapping("checkedTaskView")
  @ResponseBody
  public DWZResult checkedTaskView(String taskCode) {
    MaintainTask task = maintainTaskService.selectMaintainTaskByCode(getSiteCode(), taskCode);
    if (null == task) {
      return ajaxError(getImeViewMessageI18n(null,
          "noTaskView.M"));
    }

    return ajaxDone(null);
  }

}
